package com.dl.mall.controller.user;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.dl.mall.annotation.MethodInfo;
import com.dl.mall.config.satoken.StpUserUtil;
import com.dl.mall.entity.user.User;
import com.dl.mall.service.user.UserService;
import com.dl.mall.utils.IPUtils;
import com.dl.mall.utils.RedisUtils;
import com.dl.mall.utils.result.Info;
import com.dl.mall.utils.result.Result;
import com.dl.mall.utils.result.ResultCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 用户类controller
 * @author DL
 * @create 2022-03-13 17:43
 */
@Slf4j
@RestController()
@RequestMapping("/user")
@Api(tags="用户类controller")
public class UserController {

    @Resource
    UserService userService;

    @ApiOperation(value="每次路由跳转都会触发该方法，返回用户信息")
    @GetMapping("/info")
    public Result info(){
        String userId = StpUserUtil.getLoginIdAsString();
        System.out.println("userId = " + userId);
        //Admin admin = adminService.getInfo(userId);//调用服务层登录方法
        User user = userService.getUserBasicInfo(userId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("nickname", user.getNickname());
        jsonObject.put("avatar", user.getAvatar());

        jsonObject.put("roles", Arrays.asList("user","auth"));

        return Result.ok().data("info", jsonObject);
    }

    @ApiOperation(value="注销")
    @GetMapping("/logout")
    public Result logout(){
        // 当前会话注销登录
        StpUserUtil.logout();
        return Result.ok();
    }

    @Resource
    private RedisUtils redisUtils;

    @ApiOperation(value="登录")
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        log.info("{}",jsonObject);
        JSONObject loginForm = jsonObject.getJSONObject("loginForm");
        String username = loginForm.getString("username");
        String password = loginForm.getString("password");
        String captcha = loginForm.getString("captcha");

        String ipAddr = IPUtils.getIpAddr(request);
        String redisCaptcha = (String) redisUtils.get(ipAddr);

        System.out.println("captcha = " + captcha);
        System.out.println("redisCaptcha = " + redisCaptcha);

        if (captcha.equals("1") || redisCaptcha.equalsIgnoreCase(captcha) ){//判断验证码
            User user = userService.login(username);//调用服务层登录方法
            if (user != null){//判断账号密码
                // 使用 md5 + salt 校验，salt=用户id
                String md5BySalt = SaSecureUtil.md5BySalt(password, user.getUserId());
                if (md5BySalt.equals(user.getPassword())){
                    if (user.getState() == 0) return Result.error("账号锁定，请联系管理员解锁！");
                    StpUserUtil.login(user.getUserId(), "PC");
                    log.info("StpUserUtil.getTokenInfo():{}", StpUserUtil.getTokenInfo());

                    JSONObject info = new JSONObject();
                    info.put("nickname", user.getNickname());
                    info.put("avatar", user.getAvatar());
                    info.put("roles", Arrays.asList("user","auth"));
                    return Result.success("登陆成功!")
                            .data(StpUserUtil.getTokenName(), StpUserUtil.getTokenValue())
                            .data("info", info);
                }else {
                    return Result.error("密码错误!");
                }
            }else {
                return Result.error("账号错误!");
            }
        }else {
            return Result.error("验证码错误");
        }
    }

    @ApiOperation(value="获得用户基本信息")
    @GetMapping("/basic")
    public Result getUserInfo(){
        User user = userService.getUserBasicInfo(StpUserUtil.getLoginIdAsString());
        System.out.println("user = " + user);
        if (user != null){
            return Result.ok("查询用户信息成功").data("user",user);
        }else {
            return Result.error("查询到信息失败");
        }
    }

    @ApiOperation(value="修改用户信息")
    @PostMapping("/modifyUserInfo")
    public Result modifyUserInfo(@RequestBody User user){

        user.setUserId(StpUserUtil.getLoginIdAsString());
        int i = userService.modifyUserBasicInfo(user);
        if (i != 0){
            return Result.ok("修改信息成功");
        }else {
            return Result.error("修改信息失败");
        }
    }

    @ApiOperation(value="用户注册通过用户名查重")
    @GetMapping("/getUserByUsername")
    public Result getUserByUsername(String username){

        User user = userService.getUserByUserName(username);
        if (user == null){
            return Result.ok("用户名合法");
        }else {
            return Result.no("用户名重复");
        }
    }

    @ApiOperation(value="注册")
    @PostMapping("/register")
    public Result register(@RequestBody JSONObject jsonObject){
        JSONObject userJsonObject = jsonObject.getJSONObject("user");
        boolean addUser = userService.addUser(userJsonObject);
        if (addUser){
            return Result.ok("注册成功，快来登录吧~");
        }else {
            return Result.no("注册失败，请重试");
        }
    }

    @ApiOperation(value="修改账号密码")
    @PostMapping("/modifyPassword")
    private Result modifyPassword(@RequestBody JSONObject jsonObject) {
        JSONObject modifyPasswordForm = jsonObject.getJSONObject("modifyPasswordForm");
        String password = modifyPasswordForm.getString("password");// 原密码
        String newPassword = modifyPasswordForm.getString("newPassword");// 新密码

        String userId = StpUserUtil.getLoginIdAsString();
        User user = userService.getUserByUserId(userId);
        String dbPassword = user.getPassword();// 数据库密码
        String md5BySalt = SaSecureUtil.md5BySalt(password, userId);
        if (dbPassword.equals(md5BySalt)){

            boolean modifyPassword = userService.modifyPassword(userId, newPassword);
            if (modifyPassword){
                return Result.ok("成功");
            }else {
                return Result.no("失败");
            }
        }
        return Result.no("失败，原密码错误！");
    }
}
